<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div#test {
        background-color: cyan;
        position: absolute;
        height: 200px;
        width: 200px;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
      }
    </style>
  </head>
  <body>
    <div id="test"></div>
  </body>
  <script>
    var div = document.querySelector("#test");
    window.onkeydown = function (e) {
      // console.log(e.keyCode);
      var divStyle = window.getComputedStyle(div);
      if (e.keyCode == 65) {
        //a
        var leftPosition = parseInt(divStyle.left) - 10;

        if (leftPosition < parseInt(divStyle.width) / 2) {
          leftPosition = parseInt(divStyle.width) / 2;
        }

        div.style.left = leftPosition + "px";
      } else if (e.keyCode == 83) {
        //s
        var topPosition = parseInt(divStyle.bottom) - 10;

        if (topPosition < 0) {
          topPosition = 0;
        }

        div.style.bottom = topPosition + "px";
      } else if (e.keyCode == 68) {
        //d

        var leftPosition = parseInt(divStyle.left) + 10;

        if (
          leftPosition >
          window.innerWidth -
            parseInt(divStyle.width) +
            parseInt(divStyle.width) / 2
        ) {
          leftPosition =
            window.innerWidth -
            parseInt(divStyle.width) +
            parseInt(divStyle.width) / 2;
        }

        div.style.left = leftPosition + "px";
      } else if (e.keyCode == 87) {
        //w
        var topPosition = parseInt(divStyle.bottom) + 10;

        if (topPosition > window.innerHeight - parseInt(divStyle.height)) {
          topPosition = window.innerHeight - parseInt(divStyle.height);
        }

        div.style.bottom = topPosition + "px";
      }
    };
  </script>
</html>
